//
//  CatalogDBService.m
//  readNovels
//
//  Created by wulanzhou on 2017/2/28.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

#import "CatalogDBService.h"
#import "CatalogDAL.h"
#import "BookDBManager.h"
#import "CatalogSQL.h"
#import "BookSQL.h"
#import "Book.h"
#import "TFHpple.h"
#import "AFNetworking.h"

@implementation CatalogDBService


/// 下载目录
/// @param urlStr                      下载地址
/// @param xpath                         查询路径
/// @param coding                       编码
/// @param enumerateBlock     遍历
/// @param finished                   完成回调
- (void)downloadCatalogWithUrl:(NSString *)urlStr
                         xpath:(NSString *)xpath
                      encoding:(NSString *)coding
                          loop:(void(^)(Catalog *catalog,TFHppleElement  *element))enumerateBlock
                     completed:(void(^)(NSArray <Catalog *> *catalogs,NSError *error))finished{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
       manager.responseSerializer = [AFHTTPResponseSerializer serializer];
       [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           NSLog(@"responseObject class= %@",[responseObject class]);
           
           TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:responseObject encoding:coding]; //@"GBK"
           
            __block NSMutableArray *catalogs=[[NSMutableArray alloc] initWithCapacity:0];
           //目录读取
           NSArray * elements  = [doc searchWithXPathQuery:xpath];
           
           if (elements&&[elements count]>0) {
               [elements enumerateObjectsUsingBlock:^(TFHppleElement  *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                   
                   Catalog *item=[[Catalog alloc] init];
                   //item.serial_number = [NSString stringWithFormat:@"%d",idx];
                   item.name=[obj content];
                   //item.page_url=[NSString stringWithFormat:@"http://www.630kan.com%@",[obj objectForKey:@"href"]];
                   //item.sort = idx + 1;
                   item.ctime = [NSDate date];
                   item.mtime = [NSDate date];
                   
                   //循环block
                   if(enumerateBlock){
                       enumerateBlock(item,obj);
                   }
                   
                   [catalogs addObject:item];
               }];
           }
           
           //保存
           if(finished){
               finished(catalogs,nil);
           }
           
           
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           if (finished) {
               finished(nil,error);
           }
       }];
    
}

- (BOOL)addCatalogs:(NSArray <Catalog *> *)catalogs bookId:(NSInteger)bId{
    
    CatalogDAL *dal = [[CatalogDAL alloc] init];
    BOOL success = [dal addCatalogs:catalogs bookId:bId];
    
    if(success){
        
        NSDateFormatter*dateFormat =[[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        
        NSMutableArray *t_sql = [NSMutableArray arrayWithCapacity:0];
        NSMutableArray *args = [NSMutableArray arrayWithCapacity:0];
        [t_sql addObject:update_book_status];
        
        NSMutableArray *values = [NSMutableArray arrayWithCapacity:0];
        [values addObject:[NSNumber numberWithInteger:BookStatusCatalog]];
        [values addObject:[dateFormat stringFromDate:[NSDate date]]];
        [values addObject:[NSNumber numberWithInteger:bId]];
        [args addObject:values];
        
        
        BOOL updateStatus = [[BookDBManager shareInstance] transactionUpdataDBWithSqlArray:t_sql arguments:args];
        if (updateStatus) {
            NSLog(@"新增书籍状态成功!");
        }else{
            NSLog(@"新增书籍状态失败!");
        }
        
    }
    
   
    return success;
}

//获取未下载完成的目录
- (NSArray <Catalog *> *)getUnFinishedCatalogsWithBookId:(NSInteger)bId{

    return [[BookDBManager shareInstance] queryDBWithModels:[Catalog class] sql:query_unfinished_catalog,[NSNumber numberWithInteger:bId],[NSNumber numberWithInteger:bId], nil];

}



@end
